#pragma once
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<iostream>
#include<unistd.h>
#include<fcntl.h>

namespace ns_sock
{
    enum{
        SOCKET_ERR=1,
        BIND_ERR,
        LISTEN_ERR
    };
    const static int g_default=5;   //等待队列容量
    class Sock
    {
    public:
        static int Socket()
        {
            int sock=socket(AF_INET,SOCK_STREAM,0);
            if(sock<0)
            {
                std::cerr<<"socket error"<<std::endl;
                exit(SOCKET_ERR);
            }
            //设置TIME_OUT的状态
            int opt=1;
            setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
            return sock;
        }

        static void Bind(const int& sock,const u_int16_t & port)
        {
            struct sockaddr_in local;
            local.sin_family=AF_INET;
            local.sin_port=htons(port);
            local.sin_addr.s_addr=INADDR_ANY;
            if(bind(sock,(sockaddr*)&local,sizeof(local))<0)
            {
                std::cerr<<"bind error"<<std::endl;
                exit(BIND_ERR);
            }
            return;
        }
        static void Listen(const int& sock)
        {
            if(listen(sock,g_default)<0)
            {
                std::cerr<<"listen error"<<std::endl;
                exit(LISTEN_ERR);
            }
        }
        static void SetNonBlock(int sock)
        {
            int f1=fcntl(sock,F_GETFL);
            fcntl(sock,F_SETFL,f1|O_NONBLOCK);
        }
    };
}  